using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using MaterialDesignThemes.Wpf;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// SOP写作对话框
    /// </summary>
    public partial class SOPWritingDialog : Window
    {
        private readonly ISOPWritingService _sopWritingService;
        private readonly IFileFormatService _fileFormatService;
        private readonly IProjectService _projectService;
        private readonly ILogger<SOPWritingDialog> _logger;
        
        private readonly List<string> _selectedMaterialFiles = new();
        private CancellationTokenSource? _cancellationTokenSource;
        private bool _isGenerating = false;

        public SOPWritingDialog(
            ISOPWritingService sopWritingService,
            IFileFormatService fileFormatService,
            IProjectService projectService,
            ILogger<SOPWritingDialog> logger)
        {
            InitializeComponent();
            _sopWritingService = sopWritingService;
            _fileFormatService = fileFormatService;
            _projectService = projectService;
            _logger = logger;

            InitializeUI();
        }

        /// <summary>
        /// 初始化UI
        /// </summary>
        private void InitializeUI()
        {
            // 设置默认值
            BusinessDomainComboBox.Text = "制造业";
            
            // 设置状态
            UpdateStatus("就绪", "CheckCircle", Brushes.Green);
            
            _logger.LogInformation("SOP写作对话框已初始化");
        }

        /// <summary>
        /// 选择素材文件
        /// </summary>
        private void SelectMaterialFiles_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var openFileDialog = new OpenFileDialog
                {
                    Title = "选择素材文件",
                    Filter = "支持的文件|*.txt;*.docx;*.md|文本文件|*.txt|Word文档|*.docx|Markdown文件|*.md|所有文件|*.*",
                    Multiselect = true
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    _selectedMaterialFiles.Clear();
                    _selectedMaterialFiles.AddRange(openFileDialog.FileNames);

                    // 更新显示
                    var fileNames = _selectedMaterialFiles.Select(Path.GetFileName);
                    MaterialFilesTextBox.Text = string.Join("; ", fileNames);

                    _logger.LogInformation($"已选择 {_selectedMaterialFiles.Count} 个素材文件");
                    UpdateStatus($"已选择 {_selectedMaterialFiles.Count} 个素材文件", "FileDocument", Brushes.Blue);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "选择素材文件时发生错误");
                MessageBox.Show($"选择文件时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 开始生成SOP
        /// </summary>
        private async void StartGeneration_Click(object sender, RoutedEventArgs e)
        {
            if (_isGenerating)
            {
                // 取消生成
                _cancellationTokenSource?.Cancel();
                return;
            }

            try
            {
                // 验证输入
                if (!ValidateInputs())
                {
                    return;
                }

                _isGenerating = true;
                _cancellationTokenSource = new CancellationTokenSource();
                
                // 更新UI状态
                StartButton.Content = CreateButtonContent("Stop", "停止生成");
                StartButton.Background = Brushes.OrangeRed;
                UpdateStatus("正在生成SOP...", "Loading", Brushes.Orange);

                // 构建SOP生成请求
                var request = BuildSOPGenerationRequest();

                // 开始生成SOP
                await GenerateSOPAsync(request, _cancellationTokenSource.Token);

                if (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    UpdateStatus("SOP生成完成！", "CheckCircle", Brushes.Green);
                    MessageBox.Show("SOP生成完成！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (OperationCanceledException)
            {
                UpdateStatus("生成已取消", "Cancel", Brushes.Gray);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成SOP时发生错误");
                UpdateStatus("生成失败", "AlertCircle", Brushes.Red);
                MessageBox.Show($"生成SOP时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isGenerating = false;
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = null;
                
                // 恢复UI状态
                StartButton.Content = CreateButtonContent("Play", "开始生成");
                StartButton.Background = (Brush)FindResource("PrimaryHueMidBrush");
            }
        }

        /// <summary>
        /// 关闭对话框
        /// </summary>
        private void Close_Click(object sender, RoutedEventArgs e)
        {
            if (_isGenerating)
            {
                var result = MessageBox.Show("正在生成SOP，确定要关闭吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.No)
                {
                    return;
                }
                
                _cancellationTokenSource?.Cancel();
            }

            Close();
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        private bool ValidateInputs()
        {
            if (_selectedMaterialFiles.Count == 0)
            {
                MessageBox.Show("请选择至少一个素材文件。", "输入验证", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (SOPTypeComboBox.SelectedItem == null)
            {
                MessageBox.Show("请选择SOP类型。", "输入验证", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrWhiteSpace(BusinessDomainComboBox.Text))
            {
                MessageBox.Show("请输入业务领域。", "输入验证", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (!int.TryParse(TargetWordCountTextBox.Text, out var wordCount) || wordCount < 1000 || wordCount > 50000)
            {
                MessageBox.Show("目标字数必须在1000-50000之间。", "输入验证", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 构建SOP生成请求
        /// </summary>
        private SOPGenerationRequest BuildSOPGenerationRequest()
        {
            return new SOPGenerationRequest
            {
                Title = string.IsNullOrWhiteSpace(SOPTitleTextBox.Text) ? null : SOPTitleTextBox.Text,
                SOPType = ((ComboBoxItem)SOPTypeComboBox.SelectedItem).Content.ToString()!,
                BusinessDomain = BusinessDomainComboBox.Text,
                TargetWordCount = int.Parse(TargetWordCountTextBox.Text),
                DetailLevel = (float)DetailLevelSlider.Value,
                StandardizationLevel = (float)StandardizationLevelSlider.Value,
                MaterialFiles = _selectedMaterialFiles.ToList(),
                Structure = new SOPStructure
                {
                    IncludePurposeAndScope = IncludePurposeAndScopeCheckBox.IsChecked == true,
                    IncludeResponsibilities = IncludeResponsibilitiesCheckBox.IsChecked == true,
                    IncludeProcedures = IncludeProceduresCheckBox.IsChecked == true,
                    IncludeQualityControl = IncludeQualityControlCheckBox.IsChecked == true,
                    IncludeRiskControl = IncludeRiskControlCheckBox.IsChecked == true,
                    IncludeRecordManagement = IncludeRecordManagementCheckBox.IsChecked == true,
                    IncludeTrainingRequirements = IncludeTrainingRequirementsCheckBox.IsChecked == true,
                    IncludeRelatedDocuments = IncludeRelatedDocumentsCheckBox.IsChecked == true,
                    IncludeAppendices = IncludeAppendicesCheckBox.IsChecked == true,
                    IncludeRevisionHistory = IncludeRevisionHistoryCheckBox.IsChecked == true
                },
                OutputFormat = ((ComboBoxItem)OutputFormatComboBox.SelectedItem).Content.ToString()!,
                SaveToProject = SaveToProjectCheckBox.IsChecked == true,
                Department = string.IsNullOrWhiteSpace(DepartmentTextBox.Text) ? null : DepartmentTextBox.Text,
                Author = string.IsNullOrWhiteSpace(AuthorTextBox.Text) ? null : AuthorTextBox.Text,
                Reviewer = string.IsNullOrWhiteSpace(ReviewerTextBox.Text) ? null : ReviewerTextBox.Text,
                Approver = null, // 可以后续添加批准人字段
                UserRequirements = string.IsNullOrWhiteSpace(UserRequirementsTextBox.Text) ? null : UserRequirementsTextBox.Text
            };
        }

        /// <summary>
        /// 生成SOP
        /// </summary>
        private async Task GenerateSOPAsync(SOPGenerationRequest request, CancellationToken cancellationToken)
        {
            try
            {
                // 设置进度回调
                var progress = new Progress<string>(message =>
                {
                    Dispatcher.Invoke(() => UpdateStatus(message, "Loading", Brushes.Orange));
                });

                // 调用SOP写作服务
                var result = await _sopWritingService.GenerateSOPAsync(request, progress, cancellationToken);

                if (result.IsSuccess && !string.IsNullOrEmpty(result.Content))
                {
                    // 保存SOP
                    await SaveSOPAsync(result, request);
                }
                else
                {
                    throw new Exception(result.ErrorMessage ?? "生成SOP失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成SOP过程中发生错误");
                throw;
            }
        }

        /// <summary>
        /// 保存SOP
        /// </summary>
        private async Task SaveSOPAsync(SOPGenerationResult result, SOPGenerationRequest request)
        {
            try
            {
                string fileName;
                string fileExtension;

                // 根据输出格式确定文件扩展名
                switch (request.OutputFormat)
                {
                    case "Word文档":
                        fileExtension = ".docx";
                        break;
                    case "Markdown":
                        fileExtension = ".md";
                        break;
                    default:
                        fileExtension = ".txt";
                        break;
                }

                // 生成文件名
                var safeTitle = string.Join("_", result.Title.Split(Path.GetInvalidFileNameChars()));
                fileName = $"SOP_{safeTitle}_{DateTime.Now:yyyyMMdd_HHmmss}{fileExtension}";

                string filePath;
                // 检查是否有当前项目（通过主窗口获取）
                var mainWindow = Application.Current.MainWindow as MainWindow;
                if (request.SaveToProject && mainWindow?.CurrentProject != null)
                {
                    // 保存到项目文件夹
                    filePath = Path.Combine(mainWindow.CurrentProject.RootPath, fileName);
                }
                else
                {
                    // 让用户选择保存位置
                    var saveFileDialog = new SaveFileDialog
                    {
                        Title = "保存SOP文档",
                        FileName = fileName,
                        Filter = request.OutputFormat switch
                        {
                            "Word文档" => "Word文档|*.docx",
                            "Markdown" => "Markdown文件|*.md",
                            _ => "文本文件|*.txt"
                        }
                    };

                    if (saveFileDialog.ShowDialog() != true)
                    {
                        return;
                    }

                    filePath = saveFileDialog.FileName;
                }

                // 保存文件
                var format = request.OutputFormat switch
                {
                    "Word文档" => FileFormat.Docx,
                    "Markdown" => FileFormat.Markdown,
                    _ => FileFormat.Text
                };
                await _fileFormatService.SaveContentAsync(filePath, result.Content, format);
                result.SavedFilePath = filePath;

                _logger.LogInformation($"SOP已保存到: {filePath}");
                UpdateStatus($"SOP已保存: {Path.GetFileName(filePath)}", "CheckCircle", Brushes.Green);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存SOP时发生错误");
                throw new Exception($"保存SOP时发生错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 更新状态显示
        /// </summary>
        private void UpdateStatus(string message, string iconKind, Brush color)
        {
            StatusText.Text = message;
            StatusIcon.Kind = (PackIconKind)Enum.Parse(typeof(PackIconKind), iconKind);
            StatusIcon.Foreground = color;
        }

        /// <summary>
        /// 创建按钮内容
        /// </summary>
        private StackPanel CreateButtonContent(string iconKind, string text)
        {
            var stackPanel = new StackPanel { Orientation = Orientation.Horizontal };
            
            var icon = new PackIcon
            {
                Kind = (PackIconKind)Enum.Parse(typeof(PackIconKind), iconKind),
                Margin = new Thickness(0, 0, 8, 0)
            };
            
            var textBlock = new TextBlock { Text = text };
            
            stackPanel.Children.Add(icon);
            stackPanel.Children.Add(textBlock);
            
            return stackPanel;
        }
    }
}
